package com.example.lenovo.democ;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements IoDelStuScore{
    private ArrayList<StudentScore> scores=new ArrayList<>();
    private ListView scorelist;
    private Button addScore;
    private ScoreAdapter scoreAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化适配器
        initScoreAdapter();
        //初始化ScoreList
        initScoreList();
        //添加学生分数
        AddStuScores();
        ReadFromDB();

    }

    /**
     *  添加学生分数
     */
    private void AddStuScores() {
        addScore=findViewById(R.id.addScore);
        addScore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,AddStuScoreActivity.class);
                startActivityForResult(intent,1001);
            }
        });
    }

    /**
     *   初始化ScoreList
     */
    private void initScoreList() {
        scorelist=findViewById(R.id.scoreList);
        scorelist.setAdapter(scoreAdapter);
        scorelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                final StudentScore studentScore=scores.get(i);
                Intent intent = new Intent();
                intent.putExtra("NAME", studentScore.getName());
                intent.putExtra("ANDROID", studentScore.getAndroid());
                intent.putExtra("ENGLISH", studentScore.getEnglish());
                intent.setClass(MainActivity.this, EditStuScoreActivity.class);
                startActivityForResult(intent, 1002);
            }
        });
    }

    /**
     *  初始化适配器
     */
    private void initScoreAdapter() {
        scoreAdapter=new ScoreAdapter(MainActivity.this,scores,MainActivity.this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,  Intent data) {
        if (resultCode == 2001) {
            String name = data.getStringExtra("NAME");
            int android = data.getIntExtra("ANDROID", 0);
            int english = data.getIntExtra("ENGLISH",0);
            StudentScore studentScore=new StudentScore(name,android,english);
            AddStuScoreToDB(studentScore);
        }else if (resultCode == 3001) {
            String name = data.getStringExtra("NAME");
            int android = data.getIntExtra("ANDROID", 0);
            int english = data.getIntExtra("ENGLISH",0);
            StudentScore studentScore=new StudentScore(name,android,english);
            UpdataScoreToDB(studentScore);
        }
    }

    /**
     *   在数据库中更新学生分数信息
     */
    private void UpdataScoreToDB(StudentScore studentScore) {
        Uri uri = Uri.parse("content://cn.gdcp.djy/score");
        String where="name='"+studentScore.getName()+"'";
        ContentValues contentValues=new ContentValues();
        contentValues.put("ANDROID",studentScore.getAndroid());
        contentValues.put("ENGLISH",studentScore.getEnglish());
        int rows=getContentResolver().update(uri,contentValues,where,null);
        Toast.makeText(MainActivity.this,"共更新了"+rows+"行",Toast.LENGTH_SHORT).show();
        this.sendBroadcast(new Intent("SCO_HAD_UPDATE"));
        ReadFromDB();
    }

    /**
     *  从数据库中
     */
    private void ReadFromDB() {
        Uri uri = Uri.parse("content://cn.gdcp.djy/score");
        scores.clear();
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                String name = cursor.getString(0);
                int android=cursor.getInt(1);
                int english=cursor.getInt(2);
                StudentScore studentScore=new StudentScore(name,android,english);
                scores.add(studentScore);
            }

        }

        scoreAdapter.notifyDataSetChanged();
    }

    /**
     *   将学生的分数信息添加到数据库的分数表中
     */
    private void AddStuScoreToDB(StudentScore studentScore) {
        Uri uri = Uri.parse("content://cn.gdcp.djy/score");
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", studentScore.getName());
        contentValues.put("android", studentScore.getAndroid());
        contentValues.put("english", studentScore.getEnglish());
        getContentResolver().insert(uri,contentValues);
        this.sendBroadcast(new Intent("SCO_HAD_INSERT"));
        ReadFromDB();
    }

    @Override
    public void del(StudentScore studentScore) {
        Uri uri = Uri.parse("content://cn.gdcp.djy/score");
        String where = "name='" + studentScore.getName() + "'";
        int rows=getContentResolver().delete(uri, where, null);
        Toast.makeText(MainActivity.this,"共删除了"+rows+"行",Toast.LENGTH_SHORT).show();
        this.sendBroadcast(new Intent("SCO_HAD_DELETE"));
        ReadFromDB();
    }
}
